/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于线下支付的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-11-18
 */
package com.chnbst.bstyun.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Attach;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.model.vo.PaymentVo;
import com.chnbst.bstyun.service.AttachService;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.UserService;

/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author WangXinLei
 *
 */
@Controller
@RequestMapping("/sysAdmin")
public class PaymentAdminController {
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private AttachService attachService;
	@Autowired
	private Eos eos;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired 
	private CreateNum createNum;
	@Autowired
	private CashflowService cashflowService;
	@Autowired 
	private DealService dealService;
	@Autowired
	private GoodsService goodsService;
	
	/**
	 * @return 线下支付页面
	 * @throws Exception
	 */
	@RequestMapping(value="/payment/paymentList",method=RequestMethod.GET)
	public ModelAndView userList()throws Exception{
		return new ModelAndView("admin/paymentManager/paymentManager");
	}
	
	/**
	 * Ajax 分页查询线下支付list
	 * @return 线下支付列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/payment/paymentList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> paymentList(String page,String last)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		
		int totalRows = paymentService.selectPaymentCount(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "payment_id");
		map.put("sortOrder", "desc");
		
		List<Payment> paymentList = paymentService.selectAllPayments(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("paymentList", paymentList);
		
		return resultMap;
	}
	
	/**
	 * 根据ID查询线下支付单条数据的详细信息
	 * @return 线下支付详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/payment/paymentDetail/{paymentId}",method=RequestMethod.GET)
	public ModelAndView paymentDetail(@PathVariable Integer paymentId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		//加载线下支付的详细信息
		PaymentVo paymentInfo = paymentService.selectPaymentVoByPaymentId(paymentId);
		
		//加载线下支付的 凭证附件
		if(paymentInfo.getAttachIds().length() > 0){
			String attachIds = paymentInfo.getAttachIds();
			String str[] = attachIds.split("\\|");
			
			List<Attach> aList = new ArrayList<Attach>();
			
			for (int i = 0; i < str.length; i++) {
				Attach attach = attachService.selectAttachByAttachId(Integer.valueOf(str[i]));
				aList.add(attach);
			}
			mav.addObject("aList", aList);
		}else{
			mav.addObject("aList", null);
		}
		
		mav.addObject("paymentInfo", paymentInfo);
		mav.setViewName("admin/paymentManager/paymentDetail");
		
		return mav;
	}
	
	/**
	 * 根据ID和按钮id修改线下支付的状态
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/payment/updatePayment",method=RequestMethod.POST)
	@ResponseBody
	public boolean updatePayment(HttpServletRequest request,Integer paymentId,Integer paymentState) throws Exception{
		
		Payment payment = paymentService.selectPaymentByPaymentId(paymentId);
		payment.setPaymentId(paymentId);
		payment.setPaymentState(paymentState);
		
		boolean b = paymentService.updatePayment(payment);
		Integer orderId = payment.getOrderId();
		
		User user = userService.selectUserInfoByUserId(payment.getUserId());
		
		boolean a = true;
		boolean c = true;
		
		if(b && paymentState == 2){
			//新增现金收支明细数据
			Cashflow cashflow = new Cashflow();
			cashflow.setCashflowNum(createNum.createCashflowNum("2"));
			cashflow.setCreateTime(new Date());
			cashflow.setDealType(1);
			cashflow.setDisburseMoney(0.00);
			cashflow.setIncomeMoney(payment.getRemitMoney());
			cashflow.setOrderId(0);
			cashflow.setPayWayId(4);
			cashflow.setThenAccount(user.getAccountMoney() + payment.getRemitMoney());
			cashflow.setUserId(user.getUserId());
			cashflow.setIsCancel(0);
			
			a = cashflowService.insertCashflow(cashflow);
			
			if(payment.getDealType() == 2 ){
				//新增现金收支明细数据
				Cashflow cashflow1 = new Cashflow();
				cashflow1.setCashflowNum(createNum.createCashflowNum("2"));
				cashflow1.setCreateTime(new Date());
				cashflow1.setDealType(2);
				cashflow1.setDisburseMoney(payment.getRemitMoney());
				cashflow1.setIncomeMoney(0.00);
				cashflow1.setOrderId(payment.getOrderId());
				cashflow1.setPayWayId(4);
				cashflow1.setThenAccount(user.getAccountMoney());
				cashflow1.setUserId(user.getUserId());
				cashflow1.setIsCancel(0);
				
				c = cashflowService.insertCashflow(cashflow1);
				
				user.setInvoiceMoney(user.getInvoiceMoney()+payment.getRemitMoney());
				userService.updateUserByUserId(user);
				
			}else if(payment.getDealType() == 1 ){
				user.setAccountMoney(user.getAccountMoney()+payment.getRemitMoney());
				userService.updateAccountMoneyByUserId(user);
			}
		}
		
		//线下支付通过后开通应用
		if(b && paymentState == 2 && orderId != null) {
			
			OrderVo order = orderService.selectOrderVoByOrderId(orderId);
			
			//新增交易记录
			Deal deal = new Deal();
			deal.setDealDate(new Date());
			deal.setDealName(order.getGoodsName());
			deal.setDealNum(order.getOrderNum());
			deal.setDealState("2");
			deal.setDisburseMoney(payment.getRemitMoney());
			deal.setIncomeMoney(0.0);
			deal.setPayWayId(4);//线下支付
			deal.setUserId(order.getUserId());
			deal.setParentId(order.getParentId());
			deal.setIsCancel(0);
			dealService.insertDeal(deal);
			
			order.setPayMoney(payment.getRemitMoney());
			order.setOrderState(1);
			order.setPayByAccount(0.00);
			order.setPayByOther(0.00);
			order.setPayTime(new Date());
			order.setPayWayId(4);
			
			String result = "";
			Goods goods = goodsService.selectByGoodsId(order.getGoodsId());
			if(order.getBuyType() == 0) {
				if("0".equals(goods.getGoodsRalateGoods())) {
					result = eos.sendMeal(order);
				}else {
					result = eos.sendProduct(order);
				}
			}else {
				result = eos.sendProOrMeal(order);
			}
			
			
			if("ok".equalsIgnoreCase(result)) {
				if(order.getBuyType() == 0) {
					//激活新用户
					User newUser = userService.selectUserInfoByUserId(order.getUserId());
					newUser.setIsLive("1");
					userService.updateUserByKey(newUser);
				}
				
				//更改订单的开通状态
				order.setIsDredge(1);//0失败  1成功
			}
			orderService.updateOrderByOrderId(order);
			
		}
		
		if(a && b && c) return true ;
		else return false;
	}
}
